import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import path from 'path';
import { fileURLToPath } from 'url';

// 路由模块
import authRoutes from './routes/auth.js';
import articleRoutes from './routes/articles.js';
import userRoutes from './routes/users.js';
import uploadRoutes from './routes/upload.js';
import statsRoutes from './routes/stats.js';
import communicationRoutes from './routes/communication.js';

// ES模块获取当前目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const app = express();
const PORT = process.env.PORT || 3001;

// 中间件配置
app.use(morgan('combined')); // 请求日志
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:8080', 'http://localhost:3000'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));

app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));

// 静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/articles', articleRoutes);
app.use('/api/users', userRoutes);
app.use('/api/upload', uploadRoutes);
app.use('/api/stats', statsRoutes);
app.use('/api/communication', communicationRoutes);

// 健康检查端点
app.get('/health', (req, res) => {
  res.json({
    status: 'OK',
    message: '微前端模拟API服务器运行正常',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    version: '1.0.0'
  });
});

// API文档端点
app.get('/api', (req, res) => {
  res.json({
    name: '微前端模拟API服务器',
    version: '1.0.0',
    description: '为React主应用和Vue3子应用提供模拟后端服务',
    endpoints: {
      auth: {
        'POST /api/auth/login': '用户登录',
        'POST /api/auth/register': '用户注册',
        'POST /api/auth/logout': '用户登出',
        'GET /api/auth/me': '获取当前用户信息'
      },
      articles: {
        'GET /api/articles': '获取文章列表',
        'POST /api/articles': '创建新文章',
        'GET /api/articles/:id': '获取文章详情',
        'PUT /api/articles/:id': '更新文章',
        'DELETE /api/articles/:id': '删除文章',
        'GET /api/articles/search': '搜索文章'
      },
      users: {
        'GET /api/users': '获取用户列表',
        'GET /api/users/:id': '获取用户详情',
        'PUT /api/users/:id': '更新用户信息'
      },
      stats: {
        'GET /api/stats/dashboard': '获取仪表盘统计数据',
        'GET /api/stats/charts': '获取图表数据'
      },
      communication: {
        'POST /api/communication/message': '发送微前端消息',
        'GET /api/communication/messages': '获取消息历史',
        'POST /api/communication/sync': '同步应用状态'
      },
      upload: {
        'POST /api/upload/image': '上传图片',
        'POST /api/upload/file': '上传文件'
      }
    },
    server: {
      port: PORT,
      environment: process.env.NODE_ENV || 'development',
      timestamp: new Date().toISOString()
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'API端点不存在',
    message: `路径 ${req.originalUrl} 未找到`,
    availableEndpoints: '/api'
  });
});

// 错误处理中间件
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({
    error: '内部服务器错误',
    message: err.message,
    timestamp: new Date().toISOString()
  });
});

// 启动服务器
app.listen(PORT, () => {
  console.log('🚀 微前端模拟API服务器启动成功!');
  console.log(`📡 服务器运行在: http://localhost:${PORT}`);
  console.log(`📖 API文档: http://localhost:${PORT}/api`);
  console.log(`❤️  健康检查: http://localhost:${PORT}/health`);
  console.log('🔄 支持的前端应用:');
  console.log('   - React主应用: http://localhost:5173');
  console.log('   - Vue3子应用: http://localhost:8080');
  console.log('---'.repeat(20));
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('🛑 收到SIGTERM信号，正在关闭服务器...');
  process.exit(0);
});

process.on('SIGINT', () => {
  console.log('🛑 收到SIGINT信号，正在关闭服务器...');
  process.exit(0);
});

export default app;